<template>
<el-dialog
    :title="'导入题库'"
    :close-on-click-modal="false"
    :visible.sync="visible" >
  <el-row>
    <div class="el-form-item__content">
        <el-upload ref="upload"
            accept=".xls,.xlsx"
            action="#"
            :auto-upload="false"
            :multiple="false"
            :file-list="fileList"           
            :http-request="uploadHttpRequest"
            >
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">一次只能上传一个xls/xlsx文件，且不超过10M</div>
        </el-upload>        
    <el-button type="primary" size="small" @click="submitUpload">上 传</el-button>
    <a type="primary" href="/test.xls" size="small" >下载导入模板</a>
    </div>   
</el-row>
</el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,    
        fileList: [],        
        }
    },
    methods: {     
      init () {
        this.visible = true
      },   
    // param是默认参数，可以取得file文件信息，具体信息如下图
    uploadHttpRequest(param) {
        const formData = new FormData() //FormData对象，添加参数只能通过append('key', value)的形式添加
        formData.append('file', param.file) //添加文件对象
        formData.append('uploadType', this.rulesType)        
        this.$http({
            url: this.$http.adornUrl(`/question/question/importExcel`),
            method: 'post',
            data: formData,
            contentType: 'form'
          }).then( res => {
                const { data: { code, mark, num, msg } } = res
                if(code === 0) {
                    this.fileList = []
                    this.visible = false
                  //  param.onSuccess()  // 上传成功的文件显示绿色的对勾
                  //  this.uploadMark = mark
                  //this.$message.info('上传文件成功,导入条数:'+num)
                  this.$message({
                  message: '上传文件成功,导入条数:'+num,
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
                }else {
                    this.$message.error(msg)
                }
              
            })            
            .catch( err => {
                console.log('失败', err)
                param.onError() //上传失败的文件会从文件列表中删除
            })
    },    
    // 点击上传：手动上传到服务器，此时会触发组件的http-request
    submitUpload() {
        this.$refs.upload.submit()
    }    
    
    }
  }
</script>